package cn.getech.data.development.job.util

import java.security.{KeyFactory, Security}
import java.security.interfaces.RSAPrivateKey
import java.security.spec.PKCS8EncodedKeySpec
import java.sql.{Connection, DriverManager, Statement}
import java.util.Properties

import javax.crypto.Cipher
import org.apache.commons.codec.binary.Base64

object JdbcUtil {

  def main(args: Array[String]): Unit = {
    val a = "Ep53+epflFER0bOfz5WupqPMgIcm1pQX0rxk2jwWKNGByvNsks2IrRgRsD/cS0wXoAXGvTzcs8iX+x5qK9CobRP2dGI/qmJWovYAD+Kz7PCjQGD4lMgE1fJp8mP0TbxziJyP6zAbtV1ikLoaWCWizt2EhsX25qDj1Sju7cKH/fo="
    val str: String = rsaDecrypt(a)
    println(str)
  }


  def runPreSQL(dbType: String, preSQL: String): Int = {
    return 0
  }

  def urlFormat(dbType: String, jdbcHost: String, jdbcPort: String, dbName: String): String = {
    dbType match {
      case "mysql" => s"jdbc:mysql://${jdbcHost}:${jdbcPort}/${dbName}"
      case "oracle" => s"jdbc:oracle:thin:@//${jdbcHost}:${jdbcPort}/${dbName}"
      case "mssql" => s"jdbc:sqlserver://${jdbcHost}:${jdbcPort};DatabaseName=${dbName}"
      case "db2" => s"jdbc:db2://${jdbcHost}:${jdbcPort}/${dbName}"
      case "sqlserver" => s"jdbc:sqlserver://${jdbcHost}:${jdbcPort};DatabaseName=${dbName}"
    }
  }

  @throws(classOf[Exception])
  def runSQL(driver: String, sql: String, url: String, user: String, password: String): Unit = {
    if (driver == "") {
      throw new RuntimeException("driver is null")
    }
    val sqlList = sql.split(";")
    var connection: Connection = null
    var statement: Statement = null

    try {
      Class.forName(driver)
      connection = DriverManager.getConnection(url, user, password)
      //connection = DriverManager.getConnection(url, user, password)
      statement = connection.createStatement()
      sqlList.foreach(sql =>
        if(!"".equals(sql) && null != sql){
          statement.execute(sql.trim)
        })
    } finally {
      statement.closeOnCompletion()
      connection.close()
    }
  }

  /**
   * 私钥解密数据
   * @param content
   * @return String 解密后的数据
   */
  def rsaDecrypt(content : String): String ={
    val properties: Properties = PropertiesUtils.getProperties("common.properties")
    val privateKey: String = PropertiesUtils.getValue(properties,"privateKey")
    //val bytes: Array[Byte] = Base64.decodeBase64(stringToBytes(content))
    Security.addProvider(new com.sun.crypto.provider.SunJCE())
    val bytes: Array[Byte] = Base64.decodeBase64(content.getBytes("UTF-8"))
    val decoded: Array[Byte]  = Base64.decodeBase64(privateKey)
    val rsaPrivateKey: RSAPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)).asInstanceOf[RSAPrivateKey]

    val cipher: Cipher = Cipher.getInstance("RSA")
    cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey)
    //解密后
    val deContent: String = new String(cipher.doFinal(bytes))

    deContent
  }

  /**
   * 补位
   * @param encrytpByte
   * @return
   */
  protected def bytesToString(encrytpByte: Array[Byte]): String = {
    val result = new StringBuilder()
    for (bytes <- encrytpByte) {
      result.append(bytes.toString).append(" ")
    }
    result.mkString
  }

  /**
   * 去空位
   * @param data
   * @return
   */
  protected def stringToBytes(data: String): Array[Byte] = {
    val strings: Array[String] = data.split(" ")
    val len: Int = strings.length
    val bytes = new Array[Byte](len)
    for(i<- 0 until len){
       bytes(i) = strings(i).toByte
    }
    bytes
  }

}
